//
//  RealTimeTranscriptionViewController.swift
//  SpeechAnalyzerDemo
//
//  UIKit 版本的实时转写界面。
//

import UIKit
import Combine
import Translation


//Speech + MLKit Translate


final class RealTimeTranscriptionViewController: UIViewController {

    private let manager: SpeechAnalyzeManager
    private var cancellables = Set<AnyCancellable>()

    private let scrollView = UIScrollView()
    private let instructionsLabel = UILabel()
    private let stateLabel = UILabel()
    private let controlsStack = UIStackView()
    private let metricsContainer = UIView()
    private let metricsView = AudioMetricsView()
    private let transcriptsView = TranscriptionView()
//    private let translateView = TranscriptionView()

    
    init(manager: SpeechAnalyzeManager) {
        self.manager = manager
        super.init(nibName: nil, bundle: nil)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Real-Time"
        view.backgroundColor = .systemBackground

        setupLayout()
        configureUI()
        bindManager()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        guard isMovingFromParent else { return }
        manager.resetTranscripts()
        Task {
            do {
                try await manager.stopTranscription()
            } catch {
                manager.error = error
            }
        }
    }
}

    // MARK: - 界面布局
private extension RealTimeTranscriptionViewController {
    func setupLayout() {
        // 配置 ScrollView
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(scrollView)

        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ])

        // 配置 StackView
        let stack = UIStackView()
        stack.axis = .vertical
        stack.spacing = 24
        stack.translatesAutoresizingMaskIntoConstraints = false

        controlsStack.axis = .horizontal
        controlsStack.spacing = 16
        controlsStack.alignment = .center

        metricsContainer.translatesAutoresizingMaskIntoConstraints = false
        metricsView.translatesAutoresizingMaskIntoConstraints = false
        metricsContainer.addSubview(metricsView)

        NSLayoutConstraint.activate([
            metricsView.leadingAnchor.constraint(equalTo: metricsContainer.leadingAnchor),
            metricsView.trailingAnchor.constraint(equalTo: metricsContainer.trailingAnchor),
            metricsView.topAnchor.constraint(equalTo: metricsContainer.topAnchor),
            metricsView.bottomAnchor.constraint(equalTo: metricsContainer.bottomAnchor)
        ])

        scrollView.addSubview(stack)

        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 20),
            stack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -20),
            stack.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 24),
            stack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -24),
            stack.widthAnchor.constraint(equalTo: scrollView.widthAnchor, constant: -40)
        ])

        stack.addArrangedSubview(instructionsLabel)
        stack.addArrangedSubview(stateLabel)
        stack.addArrangedSubview(controlsStack)
        stack.addArrangedSubview(metricsContainer)
        stack.addArrangedSubview(transcriptsView)
//        stack.addArrangedSubview(translateView)

        // 设置 transcriptsView 高度为屏幕高度的 0.5
        NSLayoutConstraint.activate([
            transcriptsView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5)
        ])
    }

    func configureUI() {
        instructionsLabel.numberOfLines = 0
        instructionsLabel.textColor = .secondaryLabel
        instructionsLabel.font = .preferredFont(forTextStyle: .body)
        instructionsLabel.text = "- Capture the Audio Input\n- Transcribe in Real time"

        stateLabel.font = .preferredFont(forTextStyle: .subheadline)
        stateLabel.textColor = .secondaryLabel
        stateLabel.text = "Stopped"

        metricsContainer.isHidden = true
    }
}

    // MARK: - 数据绑定
private extension RealTimeTranscriptionViewController {
    
    func bindManager() {
        manager.$audioCapturerState
            .combineLatest(manager.$isTranscribing)
            .receive(on: RunLoop.main)
            .sink { [weak self] state, isTranscribing in
                self?.updateControls(for: state, isTranscribing: isTranscribing)
            }
            .store(in: &cancellables)

        manager.$isSettingUp
            .receive(on: RunLoop.main)
            .sink { [weak self] _ in
                guard let self else { return }
                self.updateControls(for: self.manager.audioCapturerState, isTranscribing: self.manager.isTranscribing)
            }
            .store(in: &cancellables)

        manager.$audioInputEvents
            .receive(on: RunLoop.main)
            .sink { [weak self] events in
                guard let self else { return }
                if let events {
                    self.metricsContainer.isHidden = false
                    self.metricsView.update(with: events.0, elapsed: events.1)
                } else {
                    self.metricsContainer.isHidden = true
                }
            }
            .store(in: &cancellables)

        manager.$volatileTranscript
            .combineLatest(manager.$finalizedTranscript, manager.$transcriptionConfidence)
            .receive(on: RunLoop.main)
            .sink { [weak self] volatile, finalized, confidence in
                // TranscriptionView 内部会处理断句和 tableView 更新
                self?.transcriptsView.update(finalized: finalized, volatile: volatile, confidence: confidence)
                // 开始翻译
                self?.translateText(finalized)
            }
            .store(in: &cancellables)

        manager.$showError
            .receive(on: RunLoop.main)
            .sink { [weak self] showError in
                guard
                    showError,
                    let self,
                    let error = self.manager.error
                else { return }
                self.presentError(message: error.message)
            }
            .store(in: &cancellables)
    }
    
    private func translateText(_ text: String) {

    }
}

    // MARK: - UI 更新
private extension RealTimeTranscriptionViewController {
    func updateControls(for state: AudioCapturer.EngineState, isTranscribing: Bool) {
        controlsStack.arrangedSubviews.forEach { controlsStack.removeArrangedSubview($0); $0.removeFromSuperview() }

        switch state {
        case .stopped:
            stateLabel.text = "Ready"
            let startButton = primaryButton(title: "Capture & Transcribe", color: .systemBlue, action: #selector(start))
            controlsStack.addArrangedSubview(startButton)
            startButton.heightAnchor.constraint(equalToConstant: 44).isActive = true

        case .started:
            stateLabel.text = "Transcribing"
            controlsStack.addArrangedSubview(actionButton(icon: "stop.circle", tint: .systemRed, action: #selector(stop)))
            controlsStack.addArrangedSubview(actionButton(icon: "pause.circle", tint: .systemBlue, action: #selector(pause)))

        case .paused:
            stateLabel.text = "Paused"
            controlsStack.addArrangedSubview(actionButton(icon: "stop.circle", tint: .systemRed, action: #selector(stop)))
            controlsStack.addArrangedSubview(actionButton(icon: "play.circle", tint: .systemGreen, action: #selector(resume)))
        }

        controlsStack.isUserInteractionEnabled = !manager.isSettingUp && (isTranscribing || state == .stopped)
    }

    func primaryButton(title: String, color: UIColor, action: Selector) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(title, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = color
        button.layer.cornerRadius = 8
        button.contentEdgeInsets = UIEdgeInsets(top: 12, left: 16, bottom: 12, right: 16)
        button.addTarget(self, action: action, for: .touchUpInside)
        return button
    }

    func actionButton(icon: String, tint: UIColor, action: Selector) -> UIButton {
        let button = UIButton(type: .system)
        button.setImage(UIImage(systemName: icon), for: .normal)
        button.tintColor = tint
        button.imageView?.contentMode = .scaleAspectFit
        button.widthAnchor.constraint(equalToConstant: 44).isActive = true
        button.heightAnchor.constraint(equalToConstant: 44).isActive = true
        button.addTarget(self, action: action, for: .touchUpInside)
        return button
    }

    func presentError(message: String) {
        let alert = UIAlertController(title: "Oops!", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
            self?.manager.showError = false
        })
        present(alert, animated: true, completion: nil)
    }
}

    // MARK: - 用户操作
private extension RealTimeTranscriptionViewController {
    
    @objc func start() {
        // 清空弹幕消息
        transcriptsView.clearMessages()

        Task { [weak self] in
            guard let self else { return }
            do {
                try await self.manager.startRealTimeTranscription()
            } catch {
                self.manager.error = error
            }
        }
    }

    @objc func stop() {
        Task { [weak self] in
            guard let self else { return }
            do {
                try await self.manager.stopTranscription()
                // 清空弹幕消息
//                await MainActor.run {
//                    self.transcriptsView.clearMessages()
//                }
            } catch {
                self.manager.error = error
            }
        }
    }

    @objc func pause() {
        manager.pauseRealTimeTranscription()
    }

    @objc func resume() {
        do {
            try manager.resumeRealTimeTranscription()
        } catch {
            manager.error = error
        }
    }
}
